package com.gjy.mongo.sp;

import cn.hutool.json.JSONUtil;
import org.apache.commons.codec.binary.Base64;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.convert.converter.Converter;

import java.nio.charset.StandardCharsets;

/**
 * 自定义类型转换
 *
 * @author 宫静雨
 * @version 1.0
 * @since 2023-01-30 11:32:07
 */
public class CustomConvert {

    public static final class PersonAttrsWriteConverter implements Converter<PersonAttrs, String> {

        @Override
        public String convert(@NotNull PersonAttrs source) {
            String jsonContent = JSONUtil.toJsonStr(source);
            return Base64.encodeBase64String(jsonContent.getBytes(StandardCharsets.UTF_8));
        }
    }

    public static final class PersonAttrsReadConverter implements Converter<String, PersonAttrs> {

        @Override
        public PersonAttrs convert(@NotNull String source) {
            byte[] rawContent = Base64.decodeBase64(source);
            String json = new String(rawContent, StandardCharsets.UTF_8);
            return JSONUtil.toBean(json, PersonAttrs.class);
        }
    }
}
